תוכנה 1 תרגול 2: מערכים ומבני בקרה
2 Useful Eclipse Shortcuts Ctrl+1 quick fix for errors, or small refactoring suggestions Ctrl+SPACE code content assist (auto-completion) Auto completion for main create a template for main function Auto completion for sysout system.out.println() Auto completion for for loop structures And many more, see Window > Preferences > Java > Editor > Content assist > templates Ctrl+Shift+S save changes in all open files Ctrl+Shift+F auto-formatting of the code (always use it before you submit your HW!) Ctrl+Shift+O organize imports (which allows using external classes) Ctrl+F11 run, F11 debug Alt+Shift+R rename (a variable, method, class) All the shortcuts are listed (and can be customized in Window > Preferences > General > Keys
3 מערכים Array: A fixed-length data structure for storing multiple values of the same type Example from last week: An array of odd numbers: Indices (start from 0) 0 1 2 3 4 5 6 7 odds: 1 3 5 7 9 11 13 15 The type of all elements is int odds.length == 8 The value of the element at index 4 is 9: odds[4] == 9
4 Array Variables An array is denoted by the [] notation Examples: int[] odds; int odds[]; String[] names; // legal but discouraged int[][] matrix; // an array of arrays matrix:
5 Array Creation and Initialization What is the output of the following code: int[] odds = new int[8]; for (int i = 0; i < odds.length; i++) { Output: System.out.print(odds[i] + " "); odds[i] = 2 * i + 1; System.out.print(odds[i] + " "); 0 1 0 3 0 5 0 7 0 9 0 11 0 13 0 15 Array creation: all elements get the default value for their type (0 for int)
6 Array Creation and Initialization Creating and initializing small arrays with a- priori known values: int[] odds = {1,3,5,7,9,11,13,15; String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"; Jan months:
7 Loop through Arrays By promoting the array's index: for (int i = 0; i < months.length; i++) { foreach: System.out.println(months[i]); for (String month: months) { System.out.println(month); The variable month is assigned the next element in each iteration
8 Operations on arrays The class Arrays provide operations on array Copy Sort Search Fill... java.util.arrays http://docs.oracle.com/javase/8/docs/api/java/util/arrays.html
9 Copying Arrays Assume: int[] array1 = {1,2,3; int[] array2 = {8,7,6,5; Naïve copy: array1 = array2; 8,7,6,5 array2 1,2,3 array1 What s wrong with this solution?
10 Copying Arrays Arrays.copyOf the original array the length of the copy int[] arr1 = {1, 2, 3; int[] arr2 = Arrays.copyOf(arr1, arr1.length); Arrays.copyOfRange the original array initial index of the range to be copied, inclusive final index of the range to be copied, exclusive
11 Question What is the output of the following code: int[] odds = {1, 3, 5, 7, 9, 11, 13, 15; int newodds[] = Arrays.copyOfRange(odds, 1, odds.length); for (int odd: newodds) { System.out.print(odd + " "); Output: 3 5 7 9 11 13 15
12 2D Arrays There are no 2D arrays in Java but you can build array of arrays: char[][] board = new char[3][]; for (int i = 0; i < 3; i++) board[i] = new char[3]; Or equivalently: char[][] board = new char[3][3]; board
14 2D Arrays A compact multiplication table: int[][] table = new int[10][]; for (int i = 0; i < 10; i++) { table[i] = new int[i + 1]; for (int j = 0; j <= i; j++) { table[i][j] = (i + 1) * (j + 1); 3 6 9 2 4 table 1
Fibonacci Fibonacci series 1, 1, 2, 3, 5, 8, 13, 21, 34 Definition: fib(0) = 1 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) en.wikipedia.org/wiki/fibonacci_number
16 If-Else Statement public class Fibonacci { /** Returns the n-th Fibonacci element */ public static int computeelement(int n) { if (n==0) return 1; else if (n==1) return 1; else return computeelement(n-1) + computeelement(n-2); Assumption: n 0 Can be removed
18 Switch Statement public class Fibonacci { /** Returns the n-th Fibonacci element */ public static int computeelement(int n) { switch(n) { case 0: return 1; case 1: return 1; break; default: Compilation Error: Unreachable Code Assumption: n 0 return computeelement(n-1) + computeelement(n-2);
19 Iterative Fibonacci A loop instead of a recursion static int computeelement(int n) { if (n == 0 n == 1) return 1; int prev = 1; int prevprev = 1; int curr; for (int i = 2 ; i < n ; i++) { curr = prev + prevprev; prevprev = prev; prev = curr; curr = prev + prevprev; return curr; Assumption: n 0 1 1 2 1 2 3 2 3 5 prevprev prev curr
20 נתונים במקום חישוב בתרגום רקורסיה ללולאה אנו משתמשים במשתני עזר לשמירת המצב curr, prev ו- prevprev הלולאה דיון: "זוכרת" את הנקודה שבה אנו נמצאים בתהליך החישוב יעילות לעומת פשטות. עיקרון ה- KISS )keep it simple stupid( תרגיל: כתבו את השירות computeelement )curr בלבד )ללא prevprev בעזרת prev ו-
21 For Loop Printing the first n elements: public class Fibonacci { public static int computeelement(int n) { It is better to use args[0] public static void main(string[] args) { for(int i = 0 ; i < 10 ; i++) { System.out.println(computeElement(i));
22 מודולריות, שכפול קוד ויעילות יש כאן חוסר יעילות מסוים: לולאת ה- for חוזרת גם ב- main וגם ב-.computeElement לכאורה, במעבר אחד ניתן גם לחשב את האיברים וגם להדפיס אותם כמו כן כדי לחשב איבר בסדרה איננו משתמשים בתוצאות שכבר חישבנו )של איברים קודמים( ומתחילים כל חישוב מתחילתו
23 מודולריות, שכפול קוד ויעילות מתודה )פונקציה( ערוב של חישוב צריכה לעשות דבר אחד בדיוק! והדפסה פוגע במודולריות )מדוע?( היזהרו משכפול קוד! קטע קוד דומה המופיע בשתי פונקציות שונות יגרום במוקדם או במאוחר לבאג בתוכנית )מדוע?( את בעיית היעילות )הוספת מנגנון בעזרת מערכים )תרגיל( )memoization אפשר לפתור
24 for vs. while The following two statements are almost equivalent: Variable i is not defined outside the for block for(int i = 0 ; i < n ; i++) System.out.println(computeElement(i)); int i=0; while (i < n) { System.out.println(computeElement(i)); i++;
25 while vs. do while The following two statements are equivalent if and only if n>0 : int i=0; while (i < n) { System.out.println(computeElement(i)); i++; int i=0; do { System.out.println(computeElement(i)); i++; while (i>n(;
Compilation vs. Runtime Errors 26 שגיאות קומפילציה )הידור(: שגיאות שניתן הקובץ והפיכתו ל- bytecode ע"י המהדר "לתפוס" בעת קריאת Syntax error on token "Class", class expected Class MyClass { void f() { int n=10; void g() { int m = 20; int i; System.out.println(i); דוגמאות: Syntax error, insert "" to complete MethodBody בדרך כלל קשורות ל: 26 תחביר, תאימות טיפוסים, הגדרה לפני שימוש
27 Compilation vs. Runtime Errors שגיאות זמן ריצה: לא ניתן לדעת שתהיה שגיאה במקום ספציפי בזמן ההידור )קומפילציה( a = new int[20]; int a[] = new int[10]; a[15] = 10; String s = null; System.out.println(s.length()); דוגמאות: מתקשר למנגנון החריגים,)exceptions( עליו נלמד בהמשך 27
28 Compilation vs. Runtime Errors האם יש עוד סוג של טעויות? כן, הכי גרועות, טעויות לוגיות בתוכנית public class Factorial { /** calculate x! **/ public static int factorial(int x) { int f = 0; for (int i = 2; i <= x; i++) f = f * i; return f; 28
הסוף...